package com.example.demo.controller;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/ann")
public class RedisAnnController {

    /**
     * 存入或读取缓存
     * @param id
     * @param username
     * @return
     */
    @RequestMapping("/get")
    @Cacheable(value = "spring.cache", key = "#id+#username")
    public String get(String id, String username) {
        //非空校验
        if(!StringUtils.hasLength(id) || !StringUtils.hasLength(username)) {
            return null;
        }
        System.out.println("执行了 get 方法");
        return "id: " + id + ", username: " + username;
    }

    /**
     * 更新缓存
     * 将当前方法的返回值更新到缓存中
     * @param id
     * @param username
     * @return
     */
    @RequestMapping("/put")
    @CachePut(value = "spring.cache", key = "#id+#username")
    public String put(String id, String username)  {
        //非空校验
        if(!StringUtils.hasLength(id) || !StringUtils.hasLength(username)) {
            return null;
        }
        System.out.println("执行了 put 方法");
        return "id: " + id + ", username: " + username;
    }

    /**
     * 删除缓存
     * @param id
     * @param username
     */
    @RequestMapping("/del")
    @CacheEvict(value = "spring.cache", key = "#id+#username")
    public void del(String id, String username) {
        System.out.println("执行了删除缓存");
    }

}
